package com.hmall.trade.listener;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hmall.api.ItemClient;
import com.hmall.api.PayClient;
import com.hmall.common.constants.MqConstants;
import com.hmall.dto.OrderDetailDTO;
import com.hmall.dto.PayOrderDTO;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.domain.po.OrderDetail;
import com.hmall.trade.mapper.OrderDetailMapper;
import com.hmall.trade.service.IOrderDetailService;
import com.hmall.trade.service.IOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
@RequiredArgsConstructor
public class OrderDelayMessageListener {

    private final IOrderService orderService;

    private final PayClient payClient;

    private final OrderDetailMapper orderDetailMapperMapper;
    private final ItemClient itemClient;

    @RabbitListener(bindings = @QueueBinding(
        value = @Queue(name = MqConstants.DELAY_ORDER_QUEUE_NAME),
        exchange = @Exchange(name = MqConstants.DELAY_EXCHANGE_NAME, delayed = "true"),
        key = MqConstants.DELAY_ORDER_KEY
        ))
        public void listenOrderDelayMessage(Long orderId) {
            // 1.查询订单
            Order order = orderService.getById(orderId);
            // 2.检测订单状态，判断是否已支付
            if (order == null || order.getStatus() != 1) {
                // 订单不存在或者已经支付
                return;
            }
            // 3. 未支付，需要查询支付流水状态
            PayOrderDTO payOrderDTO = payClient.queryPayOrderByBizOrderNo(orderId);

            // 4.判断是否支付

            // 4.1.已支付，标记订单状态为已支付
            if (payOrderDTO.getStatus().equals(3)) {
                orderService.markOrderPaySuccess(orderId);
            }

            // 4.2.未支付，取消订单，回滚库存
            if (order.getStatus().equals(0)){
                //取消订单，回滚库存
                orderService.cancelOrder(orderId);
                List<OrderDetailDTO> collect = orderDetailMapperMapper.selectList(new LambdaQueryWrapper<>(OrderDetail.class)
                        .eq(OrderDetail::getOrderId, orderId)).stream().map(
                        orderDetail -> {
                            OrderDetailDTO orderDetailDTO = new OrderDetailDTO();
                            orderDetailDTO.setItemId(orderDetail.getItemId());
                            orderDetailDTO.setNum(-orderDetail.getNum());
                            return orderDetailDTO;
                        }
                ).collect(Collectors.toList());
                itemClient.deductStock(collect);
            }
        }
}